<?php
namespace app\tree\model;
use app\base\model\BaseModel;
use think\Db;
use think\facade\Log;
use think\facade\Cache;
/**
 * 交互类
 */
class MutualModel extends BaseModel
{
	public $energyWater =10;
	//获得能量
	public function get_energy($data){

			
				$where_en['Token'] = $data['Token'];
				$where_en['IsReceive'] = $0;
				$where_en['isUse'] = 1;

		   
   
				
		
				$energy  = $this->loadAllData("tree_energy","energyId as flag,energyEndNum as num,energyAddTime as time,StealNum as stealNum",$where_en,1,10,"energyAddTime asc");

				log::write($this->getLastSql());
				return $energy;
				//如果找不到任何值，就新增
	

			
		
		
	}

	public function pick_energys($data,$tree,$perm){
		$energyNum=0 ; //剩余可以摘取的能量值
		$IsReceive=0;//是否被家人领取
		$energyEndNum=0;
		$StealNum =0;//被偷取的次数
		//插入养分记录表并且更新主表
		try {
			$yestoday = time()-86400;
			$where_to = [
		        ['energyId', '=', $data['flag']],
		        ['energyAddTime', '<=',$yestoday],
		        ['IsReceive', '<=', 0],
    		];
    		//判断当前能量是否成熟,判断是否已经获得过当前养分 ，即时间是否超过24小时
    		 $energy = $this->findByAttributes("tree_energy",$where_to,"energyId as flag,energyEndNum as num,energyAddTime as time,StealNum,energyInitialNum as inum");
    		 		 if(empty($energy)) return 0;
    		 if($perm['code']==10002)
   			{
   				//是好友关系
   				if(empty($energy)||$energy['inum']<4||$energy['StealNum']>3) return 0;
   				//判断可偷取的能量数值
   				switch ($energy['StealNum']) {
   					case 0:
   						$energyNum = floor($energy['inum']*0.25);
   						$energyNum==0?1:$energyNum;
   						break;
   					case 1:
   						$energyNum = floor($energy['inum']*0.25);
   						$energyNum==0?1:$energyNum;
   						break;
   					case 2:
   						$energyNum = floor($energy['inum']*0.15);
   						$energyNum==0?1:$energyNum;
   						break;
   					default:
   						return 0;
   					
   	
   			
   				}
   				$StealNum=$energy['StealNum']+1;
   			
   				
   			}else{
   				//是当前树的家庭，可直接领取全部能量
   				$IsReceive=1;
   				$energyNum = $energy['num'];
   			}
    
			
			//log::write('phase1');
			Db::startTrans();
			$energyEndNum = $energy['num']-$energyNum;//每一次能量收取过后的值
			//log::write("energyEndNum");
			//log::write($energyEndNum);
			//插入养分记录表
			$record['treesid']=$data['treeuserid'];
			$record['Token']=$data['Token'];//登录用户切换家庭的Token 能量归属家庭token
			$record['Openid']=$data['Openid']; // 被偷取的好友的Openid
			$record['Cretetime']=time();
			$record['Userid']=$data['Userid']; //登录用户Userid
			$record['energy']=$energyNum;
			$record['flag']=$data['flag'];
			$record['Iscomplete']=0;
			$record['currentenergy']=$tree['energy']+$energyNum;
			$where_tree['treesid'] =$tree['treesid'];
			$phase =$this->findAllByWhere('plant_trees_phase',$where_tree,"*",$order="treesphase desc");
			//log::write('phase');
			//log::write($phase);
        	if(empty($phase)) return 0;
        	
	        //计算能量值在哪个阶段
	        $treesphase = $this->gradefun($tree['treesid'],$record['currentenergy'],$phase);
			$record['treesphase'] =   $treesphase;
			$record['passiveOpenid'] =   $tree['openid']; //当前树创建者的Openid

			$record['passiveToken'] =   $tree['token'];  //当前树创建者的Token 被偷取的家庭Token

			$this->insert('plant_trees_record',$record);
  

			//更新当前树的能量表
			$where_user['token']=$data['Token'];
			$where_user['Iscomplete']=0;
			$user_up['treesphase'] =  $treesphase;
			$user_up['totalenergy'] =  $record['currentenergy'];
			$this->updateByWhere('plant_trees_user',$where_user,$user_up);
				//更新家庭能量表
			$where_token['token'] = $data['Token'];
			$home_energy =$this->findByAttributes('token_energy',$where_token,"totalEnergy,currentEnergy");
		
			
			$token_up['totalEnergy'] =  $energyNum+$home_energy['totalEnergy'];
			$this->updateByWhere('token_energy',$where_token,$token_up);

			//更新任务树的能量表
			$where_ener['energyId'] = $data['flag'];
			$where_ener['token'] = $tree['token'];
			$ener_up['IsReceive'] = $IsReceive;
			$ener_up['StealNum'] = $StealNum;
			$ener_up['energyEndNum'] = $energyEndNum;
			$this->updateByWhere('tree_energy',$where_ener,$ener_up);

			Db::commit();
			return 1;
		} catch (\Exception $e) {
		    // 回滚事务
		    log::write("回滚事务");
		    log::write($e->getMessage());
		    Db::rollback();
		    return 0;
		}

	}

	//通过标志位获得真正的能量值 id 树的id flag 标志位 


	 public function gradefun($treesid,$energy,$phase)//树等级函数
	{
		
		$arr =[];
		foreach ($phase as $key => $value) {
			$arr[$value['energy']] = $value['treesphase'];
		}
		//log::write($arr);
	    foreach ($arr as $key => $value)
	    {
	        if ($energy >= $key)
	        {
	        	//log::write("树的等级".$value);
	            return $value;
	        }
	    }
	    
	    return 1;
	}

	//获得树的排行榜
	public function get_ranks($data,$where_inf){

		$pre = ($data['page']-1)*$data['limit'];
		//找出所有好友的默认token所对应的树
		
		if(empty($res)||$res === false) 
		$res = Db::name('plant_trees_user')->alias('p')->field('h.totalenergy as energy,u.Usernickname as nickname,u.UserImg as image,u.Userid,u.Openid,u.defaultToken as Token')->join('userinfo u','u.Token = p.token')->join('token_energy h','h.token=p.token')->where('Iscomplete',0)->where('p.totalenergy','gt',0)->whereIn('p.Token',$where_inf)->group('u.Token')->order('energy','desc')->limit($pre,$data['limit'])->select();
	//log::write($this->g)
		//$res['sql']=$this->getLastsql();
		return $res;

	}
	
	//获得飘窗消息
	public function get_messageFloats($data){

		$where['re.Token']=$data['token'];
			$data['type'] = (isset($data['type'])&&!empty($data['type'])) ? $data['type']:1;
			
		if($data['type']==2){
			$where['re.messageFloat']=0;
		}
		$data['page'] = (isset($data['page'])&&!empty($data['page'])) ? $data['page']:1;
		$data['limit'] = (isset($data['limit'])&&!empty($data['limit'])) ? $data['limit']:10;
		$pre = ($data['page']-1)*$data['limit'];
		$message = Db::name('plant_trees_record')->alias('re')->field('re.Trecordid,re.energy as num,u.UserImg as userimg,u.Usernickname as username,re.Cretetime as time')->join('userinfo u','re.Openid = u.Openid')->where($where)->order('time','desc')->limit($pre,$data['limit'])->select();
	
		if($data['type']==2){
			$redcordids='';
			foreach ($message as $k => $v) {
				$redcordids.=$v['Trecordid'].",";
			}
			Db::name('plant_trees_record')->whereIn("Trecordid",$redcordids)->setField('messageFloat',1);
		}
		
		

		return $message;
	}

	//浇水
	public function waterings($data,$tree,$mytree){
		//判断用户是否浇水超过3次
		$yestoday =strtotime(date('Y-m-d',time())); //今天晚上12点
		$today = $yestoday+86400;//昨天12点
		//return $yestoday;
		 $where_count=[
		 	['Cretetime', '<', $today],
		    ['Cretetime', '>',$yestoday],
		    ['trecordType', '=', 1],
		    ['token','=',$data['Token']],
		    ['passiveToken','=',$data['passToken']],
		    
		 ];
		 $count = $this->countWhere('plant_trees_record',$where_count);
		
		 if($count>2) return 2;//已经交过三次水了
		 //插入记录
		 
		 try {
			Db::startTrans();
		
			//插入养分记录表
			$record['treesid']=$tree['treeuserid'];//被浇水对应的是家庭树的id 
			$record['Token']=$mytree['token'];//当前操作者的Token
			$record['Openid']=$data['openid']; //当前操作者Openid
			$record['Cretetime']=time();
			$record['Userid']=$tree['Userid']; //被浇水的树创建者Userid
			$record['energy']=$this->energyWater;
			$record['flag']=-1;
			$record['Iscomplete']=0;
			$record['currentenergy']=$tree['totalenergy']+$this->energyWater;
		
        	//更新浇水承受着的相关数据表
	        //计算能量值在哪个阶段 
	       	$where_tree['treesid'] =$tree['treesid'];
			$phase =$this->findAllByWhere('plant_trees_phase',$where_tree,"*",$order="treesphase desc");//承受者树的阶段信息
			log::write('phase');
			log::write($phase);
        	if(empty($phase)) return 0;
	        $treesphase = $this->gradefun($tree['treesid'],$record['currentenergy'],$phase);
			//$record['treesphase'] =   $treesphase;
			$record['passiveOpenid'] =   $tree['openid']; //当前树创建者的Openid

			$record['passiveToken'] =   $tree['token'];  //当前树创建者的Token
			$record['trecordType'] =   1; //类型为浇水
			$this->insert('plant_trees_record',$record);
  

			$where_user['Token'] = $tree['token'];
			$user_up['treesphase'] =  $treesphase;
			$user_up['totalenergy'] =  $record['currentenergy'];
			$this->updateByWhere('plant_trees_user',$where_user,$user_up);

			//更新家庭能量表
			$where_token['token'] = $tree['token'];
			$home_energy =$this->findByAttributes('token_energy',$where_token,"totalEnergy,currentEnergy");
			$token_up['totalEnergy'] =  $this->energyWater+$home_energy['totalEnergy'];
			$this->updateByWhere('token_energy',$where_token,$token_up);
			log::write($mytree);
			log::write("mytree");

			//更新主动浇水者的相关数据
			 $where_tree['treesid'] =$mytree['treesid'];
			$phase =$this->findAllByWhere('plant_trees_phase',$where_tree,"*",$order="treesphase desc");//承受者树的阶段信息
		
        	if(empty($phase)) return 0;
	        $treesphase = $this->gradefun($mytree['treesid'],$mytree['totalenergy'],$phase);
			//$record['treesphase'] =   $treesphase;
	
			$where_user['Token'] = $mytree['token'];
			$user_up['treesphase'] =  $treesphase;
			$user_up['totalenergy'] =  $mytree['totalenergy']-$this->energyWater;
			$this->updateByWhere('plant_trees_user',$where_user,$user_up);

			
			$where_mytoken['token'] = $mytree['token'];
			$home_myenergy =$this->findByAttributes('token_energy',$where_mytoken,"totalEnergy,currentEnergy");
			$token_myup['totalEnergy'] =  $home_myenergy['totalEnergy']-$this->energyWater;
			$this->updateByWhere('token_energy',$where_mytoken,$token_myup);
			Db::commit();
			return 1;
		} catch (\Exception $e) {
		    // 回滚事务
		     log::write('回滚事务');
		    log::write($e->getMessage());
		    Db::rollback();
		    return 0;
		}

		
	}

	//获得进度条数据
	public function get_exchanges($data){
		$res = Db::name('plant_trees_user')->alias('pt')->field('pt.totalenergy as currenergy,t.treesname,t.energy as totalenergy,t.treesid,p.name,p.imgPath')->join('plant_tree t','t.treesid=pt.treesid','right')->join('prize p','p.treeId=t.treesid')->where('pt.treeuserid',$data['treeuserid'])->find();
		return $res;
	}

	//获得家庭树的阶段
	public function getPhases($data)
	{
		$res = Db::name('plant_trees_phase')->field('energy,phaseid,treesphase,Treesimg,energy')->where('treesid',$data['treesid'])->select();
		return $res;
	}

}